/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// d3d_images.cpp - 

#include "d3d_local.h"


//
//	ED3DRenderSystem::RegisterImage
//
IImage *ED3DRenderSystem::RegisterImage(const char *name)
{
	for (uint i=0; i<image_list.size(); i++) {
		if (strcmp(name, image_list[i]->Name())==0) {
			return image_list[i];
		}
	}

	ED3DImage	*new_img = new ED3DImage(name);
	
	image_list.push_back(new_img);
	
	ap.core->CacheImage(name);

	return new_img;
}


//
//	ED3DRenderSystem::ReleaseImages
//
void ED3DRenderSystem::ReleaseImages(void)
{
	for (uint i=0; i<image_list.size(); i++) {
		delete image_list[i];
	}
	
	image_list.clear();
}


void ED3DRenderSystem::SetSampler(uint stage, const IImage *image)
{
	if (!image) {
		HRCALL( d3ddev->SetTexture(stage, NULL) );
	} else {
		const ED3DImage	*d3d_img = (const ED3DImage*)image;
		HRCALL( d3ddev->SetTexture(stage, d3d_img->Texture()) );
	}
}


void ED3DRenderSystem::SetTextureAddrMode(uint sampler, uint addr_mode)
{
	if (addr_mode == RS_TEXADDR_WRAP) {
		HRCALL( d3ddev->SetSamplerState(sampler, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP ) );
		HRCALL( d3ddev->SetSamplerState(sampler, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP ) );
		HRCALL( d3ddev->SetSamplerState(sampler, D3DSAMP_ADDRESSW, D3DTADDRESS_WRAP ) );
	} else
	if (addr_mode == RS_TEXADDR_CLAMP) {
		HRCALL( d3ddev->SetSamplerState(sampler, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP ) );
		HRCALL( d3ddev->SetSamplerState(sampler, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP ) );
		HRCALL( d3ddev->SetSamplerState(sampler, D3DSAMP_ADDRESSW, D3DTADDRESS_CLAMP ) );
	} else {
		RAISE_EXCEPTION(va("wrong texture address mode %d", addr_mode));
	}
}


/*-----------------------------------------------------------------------------
	ED3DImage
-----------------------------------------------------------------------------*/

//
//	ED3DImage::ED3DImage
//
ED3DImage::ED3DImage(const char *path)
{
	name		=	path;
	d3d_surf	=	NULL;
	
	LOG_ACTION(va("Loading : %s", path));
	
	if (strcmp(path, "*black")==0) {
		CreateSolidImage(path, 0x00, 0x00, 0x00, 0xFF);
		LOG_OK();
		return;
	}
	
	if (strcmp(path, "*red")==0) {
		CreateSolidImage(path, 0xFF, 0x00, 0x00, 0xFF);
		LOG_OK();
		return;
	}
	
	if (strcmp(path, "*green")==0) {
		CreateSolidImage(path, 0xFF, 0xFF, 0x00, 0xFF);
		LOG_OK();
		return;
	}
	
	if (strcmp(path, "*blue")==0) {
		CreateSolidImage(path, 0x00, 0x00, 0xFF, 0xFF);
		LOG_OK();
		return;
	}
	
	if (strcmp(path, "*white")==0) {
		CreateSolidImage(path, 0xFF, 0xFF, 0xFF, 0xFF);
		LOG_OK();
		return;
	}
	
	if (strcmp(path, "*playback")==0) {
		CreatePlaybackTexture(path);
		LOG_OK();
		return;
	}
	
	if (strcmp(path, "*decal")==0) {
		CreateRenderTarget(path, 4096, 4096);
		LOG_OK();
		return;
	}
	
	try 
	{
		CreateImageFromFile(path);
		LOG_OK();
	} 
	catch (exception &e) 
	{
		LOG_FAILED();
		CreateNULLImage(path);
		
		LOGF("%s\r\n", e.what());
	}
	
}


//
//	ED3DImage::~ED3DImage
//
ED3DImage::~ED3DImage(void)
{
	SAFE_RELEASE(d3d_tex);
	SAFE_RELEASE(d3d_surf);
}


//
//	ED3DImage::CreateImageFromFile
//	- loads image from disc
//
void ED3DImage::CreateImageFromFile(const char *path)
{
	LPDIRECT3DDEVICE9	d3ddev = rs->GetD3DDevice();

	IFile	*file	=	fs->FileOpen(path, FS_OPEN_READ);

	vector<byte>	buffer;
	buffer.resize(file->Size());
	file->Read(&buffer[0], file->Size());

	uint	file_size	=	file->Size();
	byte	*file_data	=	&buffer[0];
		

	D3DXIMAGE_INFO	info;

	if ( FAILED( D3DXGetImageInfoFromFileInMemory(file_data, file_size, &info) ) ) {
		fs->FileClose(file);
		RAISE_EXCEPTION(va("bad texture file \"%s\"\r\n", path));
	}
	
	if (info.ResourceType==D3DRTYPE_TEXTURE) 
	{
		LPDIRECT3DTEXTURE9 tex;
		
		if ( FAILED( D3DXCreateTextureFromFileInMemory(d3ddev, file_data, file_size, &tex) ) ) {
			fs->FileClose(file);
			RAISE_EXCEPTION(va("failed to create texture from \"%s\"\r\n", path));
		} else {
			d3d_tex	=	tex;
			width	=	info.Width;
			height	=	info.Height;
		}
	
	} else if (info.ResourceType==D3DRTYPE_CUBETEXTURE) 
	{
		LPDIRECT3DCUBETEXTURE9 tex;
		if ( FAILED( D3DXCreateCubeTextureFromFileInMemory(d3ddev, file_data, file_size, &tex) ) ) {
			fs->FileClose(file);
			RAISE_EXCEPTION(va("failed to create texture from \"%s\"\r\n", path));
		} else {
			d3d_tex	=	tex;
			width	=	info.Width;
			height	=	info.Height;
		}
	
	} else 
	{
		fs->FileClose(file);
		RAISE_EXCEPTION("Unsupported resource type");
	}
	
	
	fs->FileClose(file);
}


//
//	ED3DImage::CreateNULLImage
//	- creates image instead of disc image with a 
//	same name, when disc image does not exist
//
void ED3DImage::CreateNULLImage(const char *path)
{
	LPDIRECT3DTEXTURE9 tex;
	HRCALL( rs->GetD3DDevice()->CreateTexture(16,16, 0, D3DUSAGE_AUTOGENMIPMAP, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, NULL) );
	
	width	= 16;
	height	= 16;
	name	= path;

	D3DLOCKED_RECT rect;	
	HRCALL( tex->LockRect(0, &rect, NULL, 0) );

		byte *ptr = (byte*)rect.pBits;	
		for (uint x=0; x<16; x++) {
			for (uint y=0; y<16; y++) {
				
				byte clr[4];
				
				// All surface should be BLACK :
				clr[0] = clr[1] = clr[2] = 0x00;
				clr[3] = 0xFF;
				
				if ((x^y)&1) {				// PINK squares, it is so emotinaly
					clr[0] = clr[2] = 0xFF;	
				}
				
				if (x==15 || y==15) {		// YELLOW edge to view mapping.
					clr[0] = clr[1] = 0xFF;
					clr[2] = 0x00;
				}
				
				ptr[ y*rect.Pitch + x*4 + 0 ] = clr[2];
				ptr[ y*rect.Pitch + x*4 + 1 ] = clr[1];
				ptr[ y*rect.Pitch + x*4 + 2 ] = clr[0];
				ptr[ y*rect.Pitch + x*4 + 3 ] = clr[3];
			}
		}
	
	HRCALL( tex->UnlockRect(0) );
	
	d3d_tex	=	tex;
}


//
//	ED3DImage::CreateSolidImage
//
void ED3DImage::CreateSolidImage(const char *path, uchar r, uchar g, uchar b, uchar a)
{
	LPDIRECT3DTEXTURE9 tex;
	HRCALL( rs->GetD3DDevice()->CreateTexture(16,16, 0, D3DUSAGE_AUTOGENMIPMAP, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, NULL) );
	
	width	= 16;
	height	= 16;
	name	= path;

	D3DLOCKED_RECT rect;	
	HRCALL( tex->LockRect(0, &rect, NULL, 0) );

		byte *ptr = (byte*)rect.pBits;	
		for (uint x=0; x<16; x++) {
			for (uint y=0; y<16; y++) {
				byte clr[4] = {r,g,b,a};
				
				ptr[ y*rect.Pitch + x*4 + 0 ] = clr[2];
				ptr[ y*rect.Pitch + x*4 + 1 ] = clr[1];
				ptr[ y*rect.Pitch + x*4 + 2 ] = clr[0];
				ptr[ y*rect.Pitch + x*4 + 3 ] = clr[3];
			}
		}
	
	HRCALL( tex->UnlockRect(0) );
	
	d3d_tex	=	tex;
}


//
//	ED3DImage::CreatePlaybackTexture
//	- creates image instead of disc image with a 
//	same name, when disc image does not exist
//
void ED3DImage::CreatePlaybackTexture(const char *path)
{
	LPDIRECT3DTEXTURE9 tex;
	const uint W = 720;
	const uint H = 576;
	HRCALL( rs->GetD3DDevice()->CreateTexture(W, H, 0, D3DUSAGE_AUTOGENMIPMAP, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, NULL) );
	
	width	= W;
	height	= H;
	name	= path;

	D3DLOCKED_RECT rect;	
	HRCALL( tex->LockRect(0, &rect, NULL, 0) );

		byte *ptr = (byte*)rect.pBits;	
		for (uint x=0; x<W; x++) {
			for (uint y=0; y<H; y++) {
				
				byte clr[4];
				
				// All surface should be BLACK :
				clr[0] = clr[1] = clr[2] = 0x00;
				clr[3] = 0xFF;
				
				if ((x^y)&1) {				// PINK squares, it is so emotinaly
					clr[0] = clr[2] = 0xFF;	
				}
				
				if (x==15 || y==15) {		// YELLOW edge to view mapping.
					clr[0] = clr[1] = 0xFF;
					clr[2] = 0x00;
				}
				
				ptr[ y*rect.Pitch + x*4 + 0 ] = clr[2];
				ptr[ y*rect.Pitch + x*4 + 1 ] = clr[1];
				ptr[ y*rect.Pitch + x*4 + 2 ] = clr[0];
				ptr[ y*rect.Pitch + x*4 + 3 ] = clr[3];
			}
		}
	
	HRCALL( tex->UnlockRect(0) );
	
	d3d_tex	=	tex;
}


void ED3DImage::CreateRenderTarget(const char *path, uint w, uint h)
{
	LPDIRECT3DTEXTURE9 tex;
	
	IVar	*d3d_filter_decals = shell->RegisterVar("d3d_filter_decals", "1", 0);
	
	uint levels = 5;
	if (!d3d_filter_decals->Int()) {
		levels = 1;
	}
	
_again:	
	try {
		HRCALL_THROW( rs->GetD3DDevice()->CreateTexture(w, h, levels, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &tex, NULL) );
		HRCALL_THROW( tex->GetSurfaceLevel(0, &d3d_surf) );
	} catch (exception &e) {
		if (w<512) {
			throw;
		}
		w/=2;
		h/=2;
		goto _again;
	}
	
	width	= w;
	height	= h;
	name	= path;

	d3d_tex	=	tex;
	
	//LOGF("RT created : %dx%d\r\n", w, h);
}


/*-----------------------------------------------------------------------------
	Texture buffer access stuff :
-----------------------------------------------------------------------------*/

void ED3DImage::BeginWrite(void)
{
	LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)d3d_tex;
	HRCALL( tex->LockRect(0, &write_rect, NULL, 0) );
}

void ED3DImage::EndWrite(void)
{
	LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)d3d_tex;
	HRCALL( tex->UnlockRect(0) );
}

void ED3DImage::WritePixel(int x, int y, uint color)
{
	byte *ptr	=	(byte*)write_rect.pBits;	
	byte r		=	(color >> 24) & 0xFF;
	byte g		=	(color >> 16) & 0xFF;
	byte b		=	(color >>  8) & 0xFF;
	byte a		=	(color >>  0) & 0xFF;
	byte clr[4] = {r,g,b,a};
				
	ptr[ y*write_rect.Pitch + x*4 + 0 ] = clr[2];
	ptr[ y*write_rect.Pitch + x*4 + 1 ] = clr[1];
	ptr[ y*write_rect.Pitch + x*4 + 2 ] = clr[0];
	ptr[ y*write_rect.Pitch + x*4 + 3 ] = clr[3];
}


void ED3DImage::FilterRT(void)
{
	LPDIRECT3DTEXTURE9 tex = (LPDIRECT3DTEXTURE9)d3d_tex;

	IVar	*d3d_filter_decals = shell->RegisterVar("d3d_filter_decals", "1", 0);

	if (!d3d_filter_decals->Int()) {
		return;
	}
	
	
	uint level_count = tex->GetLevelCount();

	
	for (uint i=0; i<level_count-1; i++) {
		LPDIRECT3DSURFACE9	s1, s2;
		HRCALL_THROW( tex->GetSurfaceLevel(i,   &s1) );
		HRCALL_THROW( tex->GetSurfaceLevel(i+1, &s2) );
		
		HRCALL_THROW( rs->GetD3DDevice()->StretchRect(s1, NULL, s2, NULL, D3DTEXF_LINEAR) );
	}
}










